package com.zyy.filterconfig.filters;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.PathContainer;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

//    @Autowired
//    private AuthService authService;

    int order;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        ServerHttpRequest request = (ServerHttpRequest) exchange.getRequest();
        log.info("请求信息："+request.toString());
        // 获取请求路径
        String  url = String.valueOf(request.getURI());
        log.info(url);
        // 获取转发前的路径
        RequestPath requestPath = request.getPath();
        log.info(requestPath.toString());
        PathContainer pathContainer= requestPath.contextPath();
        log.info(pathContainer.toString());
        String a= pathContainer.value();
        log.info(a);
        MultiValueMap multipartFile=request.getQueryParams();
        log.info(multipartFile.toString());
        request.getBody();
        request.getHeaders();
        request.getMethod();
        request.getMethodValue();
        request.getLocalAddress();
        request.getRemoteAddress();
        ServerHttpResponse response = (ServerHttpResponse) exchange.getResponse();


        ResponseEntity<Boolean> responseEntity=null;

        // gateway网关Feign调用微服务异常，spring boot 2.7.0 WebFlux必须使用异步调用，同步会报错
        ExecutorService executorService = Executors.newSingleThreadExecutor();
//        Future<ResponseEntity<Boolean>> future = executorService.submit(() ->authService.authentication("token", "requestPath"));
//        try {
//            responseEntity = future.get();
//            System.out.println(responseEntity.getBody());
//        } catch (InterruptedException | ExecutionException e) {
//            e.printStackTrace();
//        }

        // 认证没有通过
        if (responseEntity.getBody()){
            log.info("gateway全局过滤器请求");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
//            Map<String, String> map=new TreeMap<>();
//            map.put("a", "a");
            JSONObject jsonObject= new JSONObject();
            jsonObject.put("a", "a");
            byte[] bits = jsonObject.toJSONString().getBytes(StandardCharsets.UTF_8);
            DataBuffer buffer = response.bufferFactory().wrap(bits);
            response.writeWith(Mono.just(buffer));
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return this.order;
    }

    public AuthFilter(int order){
        this.order=order;
    }
}
